package org.example.cloud.payment.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author wuxinxin
 */
@RestController
@RequestMapping("/hystrix")
public class HystrixTestController {

    /*@HystrixCommand(fallbackMethod = "handle",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "20000"),
            @HystrixProperty(name = "circuitBreaker.enabled",value = "false"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "1"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "90")
    })*/

    //使用yml配置
    @HystrixCommand(fallbackMethod = "handle")
    @GetMapping("/success/{id}")
    public String testSuccess(@PathVariable Integer id) throws InterruptedException {
        System.out.println("开始执行success--"+Thread.currentThread().getName()+new Date());
        Thread.sleep(100);
        int i=1/id;
        //System.out.println("执行success--"+Thread.currentThread().getName()+new Date());
        return "success";
    }


    @HystrixCommand(fallbackMethod = "handle",commandProperties = {
            @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "20000"),
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "1"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "90"),
            @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests",value ="15")
    })
    @GetMapping("/success2/{id}")
    public String testSuccess2(@PathVariable Integer id) throws InterruptedException {
        System.out.println("开始执行2success--"+Thread.currentThread().getName()+new Date());
        Thread.sleep(100);
        int i=1/id;
        //System.out.println("执行success--"+Thread.currentThread().getName()+new Date());
        return "success";
    }


    @HystrixCommand(fallbackMethod = "handle")
    @GetMapping("/failed")
    public String testFailed(Integer id) throws InterruptedException {
        Thread.sleep(300);
        System.out.println("执行failed--"+Thread.currentThread().getName()+new Date());
        return "failed";
    }


    private String handle(Integer id,Throwable throwable
    ){
        System.out.println(Thread.currentThread().getName()+"--访问错误"+throwable.getMessage());
        return "error";
    }
}
